import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => {
    // 在UniApp中使用uni.getStorageSync获取存储的用户信息
    let savedState = {};
    try {
      const savedStateStr = uni.getStorageSync('userState');
      savedState = savedStateStr ? JSON.parse(savedStateStr) : {};
    } catch (e) {
      console.error('Failed to parse userState from storage:', e);
    }
    
    return {
      userId: null,
      userName: '',
      avatar: '',
      token: '',
      role: '',
      // 如果有token则认为已登录
      isLogin: !!savedState.token,
      ...savedState
    }
  },
  actions: {
    setUserInfo(userInfo) {
      this.userId = userInfo.userId;
      this.userName = userInfo.userName;
      this.avatar = userInfo.avatar;
      this.token = userInfo.token;
      this.role = userInfo.role || '';
      this.isLogin = true;
      // 在UniApp中使用uni.setStorageSync存储用户信息
      try {
        uni.setStorageSync('userState', JSON.stringify(this.$state));
        // 同时单独存储userId和token，以便request.js可以直接访问
        uni.setStorageSync('userId', this.userId);
        uni.setStorageSync('token', this.token);
      } catch (e) {
        console.error('Failed to save userState to storage:', e);
      }
    },
    logout() {
      this.userId = null;
      this.userName = '';
      this.avatar = '';
      this.token = '';
      this.role = '';
      this.isLogin = false;
      // 在UniApp中使用uni.removeStorageSync删除存储的用户信息
      try {
        uni.removeStorageSync('userState');
        uni.removeStorageSync('userId');
        uni.removeStorageSync('token');
      } catch (e) {
        console.error('Failed to remove userState from storage:', e);
      }
    }
  }
});